package dbdata

import (
	"reflect"
	"github.com/astaxie/beego/orm"
	"fmt"
	"cloud_worm/util/umodels/mysqldb"
)

type WeaponLog struct {
	Id              int64

	WormId		    string
	WeaponId        int64
	TaskId          string

	Input           string
	ErrorInfo       string
	Output          string

	Created         int64
	Updated         int64
	Status          int
}

func (w *WeaponLog) TableName() string {
	return reflect.TypeOf(*w).Name()
}

func (w *WeaponLog) Read(fields ...string) error {
	err := orm.NewOrm().Read(w, fields...)
	if err != nil {
		return fmt.Errorf("%s, %s", w.TableName(), err.Error())
	}
	return nil
}

func (w *WeaponLog) Update(fields ...string) error {
	_, err := orm.NewOrm().Update(w, fields...)
	if err != nil {
		return fmt.Errorf("%s, %s", w.TableName(), err.Error())
	}
	return nil
}

func (w *WeaponLog) Insert() error {
	_, err := orm.NewOrm().Insert(w)
	if err != nil {
		return fmt.Errorf("%s, %s", w.TableName(), err.Error())
	}

	return nil
}

func init()  {
	orm.RegisterModel(new(WeaponLog))
}

func (w *WeaponLog) Count(wormId string, weaponId int, taskId string, status int) (int64, error) {
	qs := orm.NewOrm().QueryTable(w)
	if status != mysqldb.StatusAll {
		qs = qs.Filter("status", status)
	}
	if taskId != mysqldb.SelectStrAll {
		qs = qs.Filter("task_id__istartswith", taskId)
	}
	if weaponId != mysqldb.SelectIntAll {
		qs = qs.Filter("weapon_id", weaponId)
	}
	if wormId != mysqldb.SelectStrAll {
		qs = qs.Filter("worm_id__istartswith", wormId)
	}

	count, err := qs.Count()
	if err != nil {
		return 0, err
	}

	return count, nil
}

func (w *WeaponLog) Select(offset int, limit int, status int, wormId string, weaponId int, taskId string) ([]*WeaponLog, error) {
	var wpLogs []*WeaponLog

	qs := orm.NewOrm().QueryTable(w).Offset(offset).Limit(limit)
	if status != mysqldb.StatusAll {
		qs = qs.Filter("status", status)
	}
	if taskId != mysqldb.SelectStrAll {
		qs = qs.Filter("task_id__istartswith", taskId)
	}
	if weaponId != mysqldb.SelectIntAll {
		qs = qs.Filter("weapon_id", weaponId)
	}
	if wormId != mysqldb.SelectStrAll {
		qs = qs.Filter("worm_id__istartswith", wormId)
	}

	_, err := qs.All(&wpLogs)
	if err != nil {
		return nil, err
	}

	return wpLogs, nil
}